package com.itic.mall.system.orderjd.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itic.appbase.applications.sys.syssetting.persistence.dao.SysSettingDao;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.EmojiHelper;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.jd.MallJdConfig;
import com.itic.mall.system.marketuser.persistence.dao.MarketUserDao;
import com.itic.mall.system.marketuser.persistence.model.MarketUser;
import com.itic.mall.system.orderjd.persistence.dao.OrderJdDao;
import com.itic.mall.system.orderjd.persistence.model.OrderJd;
import com.itic.mall.system.orderjd.persistence.model.OrderJdExample;
import com.itic.mall.system.orderjdproducts.persistence.dao.OrderJdProductsDao;
import com.itic.mall.system.orderjdproducts.persistence.model.OrderJdProducts;
import com.itic.mall.system.orderjdproducts.persistence.model.OrderJdProductsExample;
import com.itic.mall.system.premoney.persistence.dao.PreMoneyDao;
import com.itic.mall.system.premoney.persistence.model.PreMoney;
import com.itic.mall.system.premoney.persistence.model.PreMoneyExample;
import com.itic.mall.system.premoney.persistence.model.PreMoneyExample.Criteria;
import com.itic.mall.system.productjd.persistence.dao.ProductJdDao;
import com.itic.mall.system.productjd.persistence.model.ProductJd;
import com.itic.mall.system.productjd.persistence.model.ProductJdExample;
import com.itic.mall.system.profitmoney.persistence.dao.ProfitMoneyDao;
import com.itic.mall.system.profitmoney.persistence.model.ProfitMoney;
import com.itic.mall.system.synctgw.persistence.dao.SyncTgwDao;
import com.itic.mall.system.synctgw.persistence.model.SyncTgw;
import com.itic.mall.system.synctgw.persistence.model.SyncTgwExample;
import com.itic.mall.system.user.persistence.dao.MallUserDao;
import com.itic.mall.system.user.persistence.model.MallUser;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.JdException;
import com.jd.open.api.sdk.request.cps.UnionServiceQueryCommissionOrdersRequest;
import com.jd.open.api.sdk.request.cps.UnionServiceQueryImportOrdersRequest;
import com.jd.open.api.sdk.response.cps.UnionServiceQueryCommissionOrdersResponse;
import com.jd.open.api.sdk.response.cps.UnionServiceQueryImportOrdersResponse;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.Notification;


@Service
@Transactional
public class OrderJdService
     extends CrudService<OrderJdDao,OrderJd,OrderJdExample> {
    @Autowired
    private OrderJdDao orderJdDao;
    @Autowired
    private SyncTgwDao syncTgwDao;
    @Autowired
    private OrderJdProductsDao orderJdProductsDao;
    @Autowired
    private SysSettingDao sysSettingDao;
    @Autowired
    private MarketUserDao marketUserDao;
    @Autowired
    private MallUserDao mallUserDao;
    @Autowired
    private PreMoneyDao preMoneyDao;
    @Autowired
    private ProfitMoneyDao profitMoneyDao;
    @Autowired
    private ProductJdDao productJdDao;
    
    private static final String APP_KEY = "97b60aeccea9d113d6a1b164";
	
	private static final String SECREAT = "fc9a01780fdeb90b43e736f3";
	
	protected static String Url = "http://120.55.205.5/webservice/sms.php?method=Submit";//发送短信的URL
    
    //同步当前一天的京东订单
  	public void syncJdOrder() {
  		//同步当前时间的订单
  		String dateStringByDate = DateHelper.getDateStringByDate(new Date(), "yyyyMMdd");
  		//subSyncJdOrder(dateStringByDate);
  		//String dateStringByDate = "20171213";
  		int hour=24;
  		for( int i=hour;i>=0;i-- ){
  			subSyncJdOrder(dateStringByDate+i+"");
  		}
      	
  	}
  	
    //同步当前一天的京东订单
  	public void syncJdOrderOneDay( String dateStringByDate ) {
  		//同步当前时间的订单
  		//String dateStringByDate = DateHelper.getDateStringByDate(new Date(), "yyyyMMdd");
  		//subSyncJdOrder(dateStringByDate);
  		//String dateStringByDate = "20171213";
  		int hour=24;
  		for( int i=hour;i>=0;i-- ){
  			subSyncJdOrder(dateStringByDate+i+"");
  		}
      			
  	}
  	
  	
  	//同步京东订单某一天的订单
  	public void syncJdOrderByDay( String dateStringByDate ) {
  		int hour=24;
  		for( int i=hour;i>=0;i-- ){
  			subSyncJdOrder(dateStringByDate+i+"");
  		}
      	
  	}
  	
  	 public void subSyncJdOrder(String daytime){
  		try {
	  	    	//以当前时间来算吧，每小时同步一次订单数据 一天同步24次，
	  	    	String SERVER_URL = MallJdConfig.getUrl();//搜索有效商品信息
	  			String accessToken = sysSettingDao.getByKey("JD_ACCESS_TOKEN");//京东TOKEN
	  	    	String appKey = MallJdConfig.getKey();
	  	    	String appSecret = MallJdConfig.getSecret();
	  	    	long unionId = MallJdConfig.getUnionId();
	  	    	
	  	    	JdClient client = new DefaultJdClient(SERVER_URL,accessToken,appKey,appSecret); 
	  			UnionServiceQueryImportOrdersRequest request=new UnionServiceQueryImportOrdersRequest();
	  			
	  			
	  			
	  			request.setUnionId( unionId );
	  			//Date dateByStringDateYYYYMMDDHH = DateHelper.getDateByStringDateYYYYMMDDHH("2017-12-"+day+" "+hour+"");
	  			//String formatDate = DateHelper.formatDate(dateByStringDateYYYYMMDDHH, "yyyyMMddHH");
	  			request.setTime( daytime );
	  			request.setPageIndex( 0 );
	  			request.setPageSize( 1000 );
	  			
  				UnionServiceQueryImportOrdersResponse response=client.execute(request);
  				
  				if( "0".equals(response.getCode()) ){
  					String ordersResult = response.getQueryImportOrdersResult();
  					//System.out.println(ordersResult);
  					if(ordersResult.contains("data")){
  						net.sf.json.JSONObject object = new net.sf.json.JSONObject();
  	  					@SuppressWarnings("static-access")
  	  					net.sf.json.JSONObject fromObject = object.fromObject(ordersResult);
  						syncData(fromObject);
  					}
  				}
  				
  			} catch (JdException e) {
  				e.printStackTrace();
  			}
  			
  	    }
  	 
  	 
  	 public void syncData( net.sf.json.JSONObject jsonObject2 ){

  			net.sf.json.JSONArray jsonArray = jsonObject2.getJSONArray("data");
  			//System.out.println(jsonArray);
  			if( jsonArray.size() > 0 ){
  				for( int i=0; i<jsonArray.size(); i++ ){
  					OrderJd orderJd2 = new OrderJd();
  					net.sf.json.JSONObject jsonObject3 = jsonArray.getJSONObject(i);
  					
  				    //获得订单信息
  					String balance = jsonObject3.getString("balance");// balance: 1:已结算，2：未结算;
  					if("2".equals(balance)){
  						orderJd2.setIsJiesuan("未结算");
  					}
  					if("1".equals(balance)){
  						orderJd2.setIsJiesuan("已结算");
  					}
  					
  					
  					String positionId = jsonObject3.getString("positionId");//positionId:推广位ID;
  					orderJd2.setTgwId(positionId);
  					//根据推广位ID获得推广位名称
  					//String tgwName = syncTgwDao.getTgwNameByTgwId(positionId);
  					
  					
  					
  					//String unionId = "ocMUlxH8I6Ucyh0OPLDbi4rtgceE";
  					String yunId = "";//订单的云店主是哪个
      				String userUnionId = "";//订单是哪个用户的
      				/*if( null != tgwName && tgwName.contains(",") ){
      					String[] split = tgwName.split(",");
      					yunId = split[0];
      					userUnionId = split[1];
      				}else{
      					yunId = tgwName;
      				}*/
      				List<SyncTgw> byTgwId = syncTgwDao.getByTgwId(positionId);
      				if( byTgwId.size()>0 ){
      					SyncTgw syncTgw = byTgwId.get(0);
      					if( null != syncTgw ){
      						orderJd2.setTgwName(syncTgw.getTgwName());
      						yunId = syncTgw.getUserId();
      					}
      				}
      				
      				//云店主肯定有
      				MarketUser marketUser = marketUserDao.selectByPrimaryKey(yunId);
  					if( null != marketUser ){
  						orderJd2.setYunUserId(marketUser.getId());
  						orderJd2.setYunUserNickName(  EmojiHelper.filterEmoji(marketUser.getUserNickName()) );
  					}else{
  						//如果没有的话，就从推广位里绑定了没有呢
  						/*yunId = syncTgwDao.getYunIdByTgwName(tgwName);
  						if( StringHelper.isNotBlank(yunId) ){
  						    //云店主肯定有
  		      				marketUser = marketUserDao.selectByPrimaryKey(yunId);
  		  					if( null != marketUser ){
  		  						orderJd2.setYunUserId(marketUser.getId());
  		  						orderJd2.setYunUserNickName(marketUser.getUserNickName());
  		  					}
  						}else{
  							orderJd2.setIsJiesuan("未匹配到推广位");
  						}*/
  						orderJd2.setIsJiesuan("未匹配到用户推广位");
  					}
      				
      				if( StringHelper.isNotBlank(userUnionId) ){
      					MallUser user = mallUserDao.getByUnionId(userUnionId);
      					if( null != user ){
      						orderJd2.setUserId(user.getId());
      						orderJd2.setUserNickName(EmojiHelper.filterEmoji(user.getUserNickName()));
      					}
      				}
      				
  					//如果推广位是ID的话，直接设置用户ID，计
  					orderJd2.setUserId(yunId);
  					
  					String orderId = jsonObject3.getString("orderId");//订单ID
  					if( "72196802004".equals(orderId)){
  						System.out.println("");
  					}
  					String id = getOrderjdId(orderId);
  					
  					orderJd2.setId(id);
  					
  					//订单号码
  					orderJd2.setOrderNum(orderId);
  					//
  					String commission = jsonObject3.getString("commission");//commission:佣金,如果是查询的引入订单接口，表示预估佣金；如果查询的是业绩订单接口，表示的是实际佣金; 
  					String marketProfit = "0";
  					if( NumberStringHelper.isGreaterNoEqual(commission, "0") ){
  						orderJd2.setCommisions(commission);
  	  					
  	  					marketProfit = getMarketProfit(commission);
  	  					orderJd2.setMarketProfit(marketProfit);
  					}else{
  						orderJd2.setCommisions("0");
  	  					orderJd2.setMarketProfit("0");
  					}
  					
  					
  					String cosPrice = jsonObject3.getString("cosPrice");//cosPrice:订单实际计算佣金使用金额; 
  					orderJd2.setOrderTotalMoney(cosPrice);
  					Long finishTime = jsonObject3.getLong("finishTime");//订单完成时间
  					if( 0!=finishTime ){
  						orderJd2.setFinishTime(DateHelper.formatDateTime(new Date(finishTime)));
  						//orderJd2.setIsJiesuan("已结算");
  					}else{
  						orderJd2.setFinishTime("");
  						//orderJd2.setIsJiesuan("未结算");
  					}
  					
  					Long orderTime = jsonObject3.getLong("orderTime");//订单时间
  					//String dateStringByDate = DateHelper.getDateStringByDate(,"yyyy-MM-dd HH:mm:ss");
  					orderJd2.setOrderDate(new Date(orderTime));
  					
  					String parentId = jsonObject3.getString("parentId");//parentId:父单ID,父单拆分后,子单中parentId为父单的id;
  					orderJd2.setParentId(parentId);
  					String plus = jsonObject3.getString("plus");//plus:是否plus会员 1是，0不是;
  					orderJd2.setIsPlus(plus);
  					String popId = jsonObject3.getString("popId");//popId:商家ID; 
  					orderJd2.setPopId(popId);
  					
  					String sourceEmt = jsonObject3.getString("sourceEmt");// sourceEmt:下单设备 1.pc 2.无线;
  					if( "1".equals(sourceEmt) ){
  						orderJd2.setDeviceType("PC");
  					}
  					if( "2".equals(sourceEmt) ){
  						orderJd2.setDeviceType("无线");
  					}
					//orderJd2.setDeviceType(sourceEmt);
					//String splitType = jsonObject3.getString("splitType");//splitType:拆分类型固定为3;
					String totalMoney = jsonObject3.getString("totalMoney");//订单金额（会员价 包含优惠，不含运费,是各个商品会员价的总和); 
					orderJd2.setOrderTotalMoney(totalMoney);
					String unionTrafficType = jsonObject3.getString("unionTrafficType");//unionTrafficType:渠道来源，
					orderJd2.setSource(unionTrafficType);
					String yn = jsonObject3.getString("yn"); //yn:订单取消标识，1买家未取消，0买家已取消
					if( "0".equals(yn) ){
						orderJd2.setIsCancel("买家已取消");
					}
					if( "1".equals(yn) ){
						orderJd2.setIsCancel("买家未取消");
					}
					//orderJd2.setIsCancel(yn);
					
					//保存一份到我们的数据
    				if(StringHelper.isNotBlank(orderJd2.getId())){
    					orderJdDao.updateByPrimaryKeySelective(orderJd2);
    				}else{
    					this.initDefalutFields(orderJd2);
    					orderJdDao.insert(orderJd2);
    				}
					
				    //新建多条sku数据
					String totalCount = "0";
					String productName = "";
					net.sf.json.JSONArray jsonArray2 = jsonObject3.getJSONArray("skus");
					if( jsonArray2.size()>0 ){
						for( int j=0; j<jsonArray2.size(); j++ ){
							net.sf.json.JSONObject jsonObject4 = jsonArray2.getJSONObject(j);
							OrderJdProducts orderP = new OrderJdProducts();
							
							//this.initDefalutFields(orderP);
							String skuId = jsonObject4.getString("skuId");//skuId
							ProductJd bySku = getBySku(skuId);
							/*OrderJdProductsParamVo paramVo = new OrderJdProductsParamVo();
							paramVo.setSkuId(skuId);
							paramVo.setOrderId(orderJd2.getId());
							String orderPId = orderJdProductsDao.getOrderJdProductsIdBySkuIdAndOrderId(paramVo);*/
							String orderPId = getOrderJdProductsIdBySkuIdAndOrderId( skuId,orderJd2.getId() );
							
							orderP.setId(orderPId);
							
							String commissionSku = jsonObject4.getString("commission");//commission:佣金(cosPrice * commissionRate); 
							String commissionRate = jsonObject4.getString("commissionRate");//commissionRate:佣金比例; 
							String cosPriceSku = jsonObject4.getString("cosPrice");//cosPrice:用于佣金计算的基础值; 
							orderP.setSkuTotalPrice(cosPriceSku);
							String firstLevel = jsonObject4.getString("firstLevel");//firstLevel:一级类目;
							orderP.setOneCategory(firstLevel);
							//String pid = jsonObject4.getString("pid");//pid：子站长ID_子站长网站ID_子站长推广位ID  
							//orderP.setTopId(pid);
							
							String price = jsonObject4.getString("price");//sku价格
							
							String secondLevel = jsonObject4.getString("secondLevel");//firstLevel:一级类目;
							orderP.setTwoCategory(secondLevel);
							
							String skuName = jsonObject4.getString("skuName");//商品名称
							productName = skuName;
							String skuNum = jsonObject4.getString("skuNum");// skuNum:商品数量; 
							totalCount = NumberStringHelper.addString(totalCount, skuNum);
							
							String skuReturnNum = jsonObject4.getString("skuReturnNum");//skuReturnNum:商品退货数量;
							orderP.setSkuBackNum(skuReturnNum);
							String subSideRate = jsonObject4.getString("subSideRate");//subSideRate:分佣方的分佣比例(收入分成比例); 
							orderP.setJdShouchenRate(subSideRate);
							//String subUnionId = jsonObject4.getString("subUnionId");//subUnionId:子联盟ID(需要联系运营开放白名单才能拿到数据);
							//orderP.setSubUnionId(subUnionId);
							
							String subsidyRate = jsonObject4.getString("subsidyRate");//subsidyRate:平台分成比例;
							orderP.setShouchenRate(subsidyRate);
							
							String thirdLevel = jsonObject4.getString("thirdLevel");//firstLevel:一级类目;
							orderP.setThreeCategory(thirdLevel);
							
							String unionAlias = jsonObject4.getString("unionAlias");//unionAlias：母站长简称，
							orderP.setTopPcName(unionAlias);
							
							String valid = jsonObject4.getString("valid");//valid:sku是否有效字段,1:有效，2：无效;
							orderP.setSkuIsValid(valid);
							String validCode = jsonObject4.getString("validCode");//validCode:无效码 1:有效,2:订单拆单,3:订单取消,4:京东帮帮主订单,5:账户异常,6:赠品类目,7:校园订单,8:企业订单,9:团购订单,10:开增值税专用发票订单,11:乡村推广员下单,12:自己推广自己下单,13:违规订单,14:订单来源与备案网址不符,-1:无效原因未知
							orderP.setSkuValidCode(validCode);
							String wareId = jsonObject4.getString("wareId");//wareId:款ID; 
							orderP.setWareId(wareId);
							
  				        	orderP.setOrderId(orderJd2.getId());
  				        	orderP.setSkuPrice(price);
  				        	orderP.setSkuId(skuId);
  				        	if( null != bySku ){
  				        		orderP.setSkuImgUrl(bySku.getGoodsUrl());
  				        	}
  				        	
  				        	orderP.setSkuName(skuName);
  				        	orderP.setSkuNum(skuNum);
  				        	orderP.setCommissionRate(commissionRate);
  				        	orderP.setCommissions(commissionSku);
  				        	
  				        	
  				            //保存一份到我们的数据
  		    				if( StringHelper.isNotBlank(orderP.getId()) ){
  		    					orderJdProductsDao.updateByPrimaryKeySelective(orderP);
  		    				}else{
  		    					this.initDefalutFields(orderP);
  		    					orderJdProductsDao.insert(orderP);
  		    				}
  				        	
						}
					}
						
					
					//添加
					if( "1".equals(yn) && "2".equals(balance) ){
						PreMoneyExample exampleP = new PreMoneyExample();
	                    Criteria criteria = exampleP.createCriteria();
	                    criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	                    criteria.andOrderNumEqualTo(orderId);
	 	    		    List<PreMoney> listP = preMoneyDao.selectByExample(exampleP);
	    				if( listP.size()==0 ){
    						if( null != marketUser && NumberStringHelper.isGreaterNoEqual(marketProfit, "0") ){
    							addTopJdPreMoney(marketUser,marketProfit,orderId,cosPrice,productName,EmojiHelper.filterEmoji(orderJd2.getYunUserNickName()),orderJd2.getOrderDate());
    						}
	    				}
					}
					
					if(  "0".equals(yn) ){
	 	    		    //取消根据预计收益
    					cancelPreMoney(orderId);
					}
					
  				}
  		}
   }
  	 
  	 /**
  	  * 根据某个订单ID同步
  	  * @param orderid
  	  * @return
  	  */
  	 public Map<String,String> nowsync( OrderJd orderjd ){
  		 Map<String, String> result = new HashMap<String,String>();
  		 String res = "error";
  		 String msg = "服务器异常！";
  		 String tgwId = orderjd.getTgwId();
  		 SyncTgwExample example = new SyncTgwExample();
  		 com.itic.mall.system.synctgw.persistence.model.SyncTgwExample.Criteria criteria = example.createCriteria();
  		 criteria.andIsEffectiveEqualTo(DBConst.TRUE);
  		 criteria.andTgwIdEqualTo(tgwId);
  		 
  		 List<SyncTgw> list = syncTgwDao.selectByExample(example);
  		 if( list.size()==1 ){
  			SyncTgw syncTgw = list.get(0); 
  			
  			if(  StringHelper.isNotBlank(syncTgw.getUserId()) ){
  				MarketUser marketUser = marketUserDao.selectByPrimaryKey(syncTgw.getUserId());
  				if( null != marketUser ){
  					OrderJdProductsExample example2 = new OrderJdProductsExample();
  					com.itic.mall.system.orderjdproducts.persistence.model.OrderJdProductsExample.Criteria criteria2 = example2.createCriteria();
  					criteria2.andOrderIdEqualTo(orderjd.getId());
  					List<OrderJdProducts> list2 = orderJdProductsDao.selectByExample(example2);
  					if( list2.size()==1 ){
  						OrderJdProducts jdProducts = list2.get(0);
  						addTopJdPreMoney(marketUser,orderjd.getMarketProfit(),orderjd.getOrderNum(),orderjd.getOrderTotalMoney(),jdProducts.getSkuName(),marketUser.getUserNickName(),orderjd.getOrderDate());
  						orderjd.setIsJiesuan("未结算");
  						orderjd.setYunUserId(marketUser.getId());
  						orderjd.setYunUserNickName(marketUser.getUserNickName());
  						orderJdDao.updateByPrimaryKey(orderjd);
  						res = "success";
  						msg = "同步成功！";
  					}else{
  						msg = "异常订单项！";
  					}
  					
  				}else{
  					msg = "推广位未找到店主！";
  				}
  			}else{
  				msg = "推广位未关联到店主！";
  			}
  		 }else{
  			msg = "未创建推广位！";
  		 }
  		 result.put("result", res);
  		 result.put("msg", msg);
  		 return result;
  	 }
  	 
  	 public void syncDataOver( net.sf.json.JSONObject jsonObject2 ){

			net.sf.json.JSONArray jsonArray = jsonObject2.getJSONArray("data");
			//System.out.println(jsonArray);
			if( jsonArray.size() > 0 ){
				for( int i=0; i<jsonArray.size(); i++ ){
					OrderJd orderJd2 = new OrderJd();
					net.sf.json.JSONObject jsonObject3 = jsonArray.getJSONObject(i);
					
				    //获得订单信息
					String balance = jsonObject3.getString("balance");// balance: 1:已结算，2：未结算;
					if("2".equals(balance)){
						orderJd2.setIsJiesuan("未结算");
					}
					if("1".equals(balance)){
						orderJd2.setIsJiesuan("已结算");
					}
					
					
					String positionId = jsonObject3.getString("positionId");//positionId:推广位ID;
					orderJd2.setTgwId(positionId);
					//根据推广位ID获得推广位名称
					//String tgwName = syncTgwDao.getTgwNameByTgwId(positionId);
					
					//String unionId = "ocMUlxH8I6Ucyh0OPLDbi4rtgceE";
					String yunId = "";//订单的云店主是哪个
	   				String userUnionId = "";//订单是哪个用户的
	   				List<SyncTgw> byTgwId = syncTgwDao.getByTgwId(positionId);
	   				if(  byTgwId.size()>0 ){
	   					SyncTgw syncTgw = byTgwId.get(0);
	  					if( null != syncTgw ){
	  						orderJd2.setTgwName(syncTgw.getTgwName());
	  						yunId = syncTgw.getUserId();
	  						orderJd2.setUserId(yunId);
	  					}
	   				}
	   				//云店主肯定有
	   				MarketUser marketUser = marketUserDao.selectByPrimaryKey(yunId);
					if( null != marketUser ){
						orderJd2.setYunUserId(marketUser.getId());
						orderJd2.setYunUserNickName(EmojiHelper.filterEmoji(marketUser.getUserNickName()));
					}else{
						//如果没有的话，就从推广位里绑定了没有呢
						/*yunId = syncTgwDao.getYunIdByTgwName(tgwName);
						if( StringHelper.isNotBlank(yunId) ){
						    //云店主肯定有
		      				marketUser = marketUserDao.selectByPrimaryKey(yunId);
		  					if( null != marketUser ){
		  						orderJd2.setYunUserId(marketUser.getId());
		  						orderJd2.setYunUserNickName(marketUser.getUserNickName());
		  					}
						}else{
							orderJd2.setIsJiesuan("未匹配到推广位");
						}*/
						orderJd2.setIsJiesuan("未匹配到推广位");
					}
   				
	   				if( StringHelper.isNotBlank(userUnionId) ){
	   					MallUser user = mallUserDao.getByUnionId(userUnionId);
	   					if( null != user ){
	   						orderJd2.setUserId(user.getId());
	   						orderJd2.setUserNickName(EmojiHelper.filterEmoji(user.getUserNickName()));
	   					}
	   				}
	   				
					//如果推广位是ID的话，直接设置用户ID，计
					//orderJd2.setUserId(tgwName);
					
					String orderId = jsonObject3.getString("orderId");//订单ID
					if( orderId.equals("72194287951")){
						System.out.println("72194287951");
					}
					String id = getOrderjdId(orderId);
					
					orderJd2.setId(id);
					
					//订单号码
					orderJd2.setOrderNum(orderId);
					//
					String commission = jsonObject3.getString("commission");//commission:佣金,如果是查询的引入订单接口，表示预估佣金；如果查询的是业绩订单接口，表示的是实际佣金; 
					String marketProfit = "0";
					if( NumberStringHelper.isGreaterNoEqual(commission, "0") ){
						orderJd2.setCommisions(commission);
	  					
	  					marketProfit = getMarketProfit(commission);
	  					orderJd2.setMarketProfit(marketProfit);
					}else{
						orderJd2.setCommisions("0");
	  					orderJd2.setMarketProfit("0");
					}
					
					
					String cosPrice = jsonObject3.getString("cosPrice");//cosPrice:订单实际计算佣金使用金额; 
					orderJd2.setOrderTotalMoney(cosPrice);
					Long finishTime = jsonObject3.getLong("finishTime");//订单完成时间
					if( 0!=finishTime ){
						orderJd2.setFinishTime(DateHelper.formatDateTime(new Date(finishTime)));
						//orderJd2.setIsJiesuan("已结算");
					}else{
						orderJd2.setFinishTime("");
						//orderJd2.setIsJiesuan("未结算");
					}
					
					Long orderTime = jsonObject3.getLong("orderTime");//订单时间
					//String dateStringByDate = DateHelper.getDateStringByDate(,"yyyy-MM-dd HH:mm:ss");
					orderJd2.setOrderDate(new Date(orderTime));
					
					String parentId = jsonObject3.getString("parentId");//parentId:父单ID,父单拆分后,子单中parentId为父单的id;
					orderJd2.setParentId(parentId);
					String plus = jsonObject3.getString("plus");//plus:是否plus会员 1是，0不是;
					orderJd2.setIsPlus(plus);
					String popId = jsonObject3.getString("popId");//popId:商家ID; 
					orderJd2.setPopId(popId);
					
					String sourceEmt = jsonObject3.getString("sourceEmt");// sourceEmt:下单设备 1.pc 2.无线;
					if( "1".equals(sourceEmt) ){
						orderJd2.setDeviceType("PC");
					}
					if( "2".equals(sourceEmt) ){
						orderJd2.setDeviceType("无线");
					}
					//orderJd2.setDeviceType(sourceEmt);
					//String splitType = jsonObject3.getString("splitType");//splitType:拆分类型固定为3;
					String totalMoney = jsonObject3.getString("totalMoney");//订单金额（会员价 包含优惠，不含运费,是各个商品会员价的总和); 
					orderJd2.setOrderTotalMoney(totalMoney);
					String unionTrafficType = jsonObject3.getString("unionTrafficType");//unionTrafficType:渠道来源，
					orderJd2.setSource(unionTrafficType);
					String yn = jsonObject3.getString("yn"); //yn:订单取消标识，1买家未取消，0买家已取消
					if( "0".equals(yn) ){
						orderJd2.setIsCancel("买家已取消");
					}
					if( "1".equals(yn) ){
						orderJd2.setIsCancel("买家未取消");
					}
					//orderJd2.setIsCancel(yn);
					
					//保存一份到我们的数据
	 				if(StringHelper.isNotBlank(orderJd2.getId())){
	 					orderJdDao.updateByPrimaryKeySelective(orderJd2);
	 				}else{
	 					this.initDefalutFields(orderJd2);
	 					orderJdDao.insert(orderJd2);
	 				}
					
				    //新建多条sku数据
					String totalCount = "0";
					String productName = "";
					net.sf.json.JSONArray jsonArray2 = jsonObject3.getJSONArray("skus");
					if( jsonArray2.size()>0 ){
						for( int j=0; j<jsonArray2.size(); j++ ){
							net.sf.json.JSONObject jsonObject4 = jsonArray2.getJSONObject(j);
							OrderJdProducts orderP = new OrderJdProducts();
							
							//this.initDefalutFields(orderP);
							String skuId = jsonObject4.getString("skuId");//skuId
							ProductJd bySku = getBySku(skuId);
							/*OrderJdProductsParamVo paramVo = new OrderJdProductsParamVo();
							paramVo.setSkuId(skuId);
							paramVo.setOrderId(orderJd2.getId());
							String orderPId = orderJdProductsDao.getOrderJdProductsIdBySkuIdAndOrderId(paramVo);*/
							String orderPId = getOrderJdProductsIdBySkuIdAndOrderId( skuId,orderJd2.getId() );
							
							orderP.setId(orderPId);
							
							String commissionSku = jsonObject4.getString("commission");//commission:佣金(cosPrice * commissionRate); 
							String commissionRate = jsonObject4.getString("commissionRate");//commissionRate:佣金比例; 
							String cosPriceSku = jsonObject4.getString("cosPrice");//cosPrice:用于佣金计算的基础值; 
							orderP.setSkuTotalPrice(cosPriceSku);
							String firstLevel = jsonObject4.getString("firstLevel");//firstLevel:一级类目;
							orderP.setOneCategory(firstLevel);
							//String pid = jsonObject4.getString("pid");//pid：子站长ID_子站长网站ID_子站长推广位ID  
							//orderP.setTopId(pid);
							
							String price = jsonObject4.getString("price");//sku价格
							
							String secondLevel = jsonObject4.getString("secondLevel");//firstLevel:一级类目;
							orderP.setTwoCategory(secondLevel);
							
							String skuName = jsonObject4.getString("skuName");//商品名称
							productName = skuName;
							String skuNum = jsonObject4.getString("skuNum");// skuNum:商品数量; 
							totalCount = NumberStringHelper.addString(totalCount, skuNum);
							
							String skuReturnNum = jsonObject4.getString("skuReturnNum");//skuReturnNum:商品退货数量;
							orderP.setSkuBackNum(skuReturnNum);
							String subSideRate = jsonObject4.getString("subSideRate");//subSideRate:分佣方的分佣比例(收入分成比例); 
							orderP.setJdShouchenRate(subSideRate);
							//String subUnionId = jsonObject4.getString("subUnionId");//subUnionId:子联盟ID(需要联系运营开放白名单才能拿到数据);
							//orderP.setSubUnionId(subUnionId);
							
							String subsidyRate = jsonObject4.getString("subsidyRate");//subsidyRate:平台分成比例;
							orderP.setShouchenRate(subsidyRate);
							
							String thirdLevel = jsonObject4.getString("thirdLevel");//firstLevel:一级类目;
							orderP.setThreeCategory(thirdLevel);
							
							String unionAlias = jsonObject4.getString("unionAlias");//unionAlias：母站长简称，
							orderP.setTopPcName(unionAlias);
							
							String valid = jsonObject4.getString("valid");//valid:sku是否有效字段,1:有效，2：无效;
							orderP.setSkuIsValid(valid);
							String validCode = jsonObject4.getString("validCode");//validCode:无效码 1:有效,2:订单拆单,3:订单取消,4:京东帮帮主订单,5:账户异常,6:赠品类目,7:校园订单,8:企业订单,9:团购订单,10:开增值税专用发票订单,11:乡村推广员下单,12:自己推广自己下单,13:违规订单,14:订单来源与备案网址不符,-1:无效原因未知
							orderP.setSkuValidCode(validCode);
							String wareId = jsonObject4.getString("wareId");//wareId:款ID; 
							orderP.setWareId(wareId);
							
				        	orderP.setOrderId(orderJd2.getId());
				        	orderP.setSkuPrice(price);
				        	orderP.setSkuId(skuId);
				        	if( null != bySku ){
				        		orderP.setSkuImgUrl(bySku.getGoodsUrl());
				        	}
				        	
				        	orderP.setSkuName(skuName);
				        	orderP.setSkuNum(skuNum);
				        	orderP.setCommissionRate(commissionRate);
				        	orderP.setCommissions(commissionSku);
				        	
				        	
				            //保存一份到我们的数据
		    				if( StringHelper.isNotBlank(orderP.getId()) ){
		    					orderJdProductsDao.updateByPrimaryKeySelective(orderP);
		    				}else{
		    					this.initDefalutFields(orderP);
		    					orderJdProductsDao.insert(orderP);
		    				}
				        	
						}
					}
						
					//结算的订单
					if( "1".equals(yn) && "1".equals(balance) ){
						//查看有没有预计收益，如果有就结算，如果没有就新建预计收益和实际收益
						PreMoneyExample exampleP = new PreMoneyExample();
						Criteria criteria = exampleP.createCriteria();
						criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	                    criteria.andOrderNumEqualTo(orderId);
	 	    		    List<PreMoney> listP = preMoneyDao.selectByExample(exampleP);
	 	    		    
	    				if( listP.size()==0 ){//这是没有算预计收益的订单
	    					if( null != marketUser && NumberStringHelper.isGreaterNoEqual(marketProfit, "0") ){
	    						addTopJdPreMoneyOver(marketUser,orderJd2,productName);
	 						}else{
	 							orderJd2.setIsJiesuan("未匹配到推广位");
	 							orderJdDao.updateByPrimaryKeySelective(orderJd2);
	 						}
	    				}else{
	    					//结算收益并且之前有算过预计收益的
	    					jiesuan(listP,orderJd2, new Date(finishTime), commission,productName);
	    				}
	    				
	    				
		    		}
					
				}
		}
}   
  	 
	
  	 
	/**
  	  * 添加上级和上上级的预计收益
  	  * @param user
  	  * @param money
  	  */
  	public void addTopJdPreMoney( MarketUser user, String money, String orderNum,String orderTotalMoney,String productName,String tgwName,Date orderDate){
  		
  		//List<MarketUser> marketUsers = new ArrayList<MarketUser>();//可为null
		//List<MarketProfit> marketProfits = new ArrayList<MarketProfit>();
		List<PreMoney> preMoneys = new ArrayList<PreMoney>();
		
		//给店主的佣金
		//String noteUser = "VIP用户***在京东购买了您分享的商品,预计获得佣金"+money+"元！";
		String noteUser = "您分享的京东商品【"+productName+"】已有人购买生成订单"+orderTotalMoney+"元，预计将获得佣金"+money+"元！";
		
		PreMoney preMoneyUser = getPreMoney( user.getId(),orderNum,orderTotalMoney,money,noteUser,orderDate);
		preMoneys.add(preMoneyUser);
		//添加云店用户
	    //marketUsers.add(resetMarketUserPreMoney(user,money));
	    
		//添加云店用户
	    sendMsgToUserOnly(user, noteUser);
  	    //添加三级分销的功能提成
		String one = sysSettingDao.getByKey("MARKET_SET_ONE_PEOPLE");
		String two = sysSettingDao.getByKey("MARKET_SET_TWO_PEOPLE");
		String onePercent = sysSettingDao.getByKey("MARKET_SET_ONE_PERCENT");
		String twoPercent = sysSettingDao.getByKey("MARKET_SET_TWO_PERCENT");
		//查找商家的上级信息，是否满足一级条件，如果满足则添加相应的金额 
		MarketUser invitingUser = marketUserDao.selectByPrimaryKey(user.getInvitingId());
		String successPeople = "0";
		if( null != invitingUser && StringHelper.isNotBlank(invitingUser.getSuccessPeople()) ){
			successPeople = invitingUser.getSuccessPeople();
		}
		//添加上级的预计收益信息
		if( null != invitingUser ){
			
			if( NumberStringHelper.isGreater(successPeople, one ) ){
				String moneyOne = getPercentMoney(money, onePercent );
				//添加预计收益记录
				//String note = "VIP用户***成功付款,预计赚取下级店主“"+user.getUserNickName()+"”的佣金提成"+moneyOne+"元!";
				String note = "您的一级云店主【"+tgwName+"】分享了京东商品《"+productName+"》已有人购买生成订单"+orderTotalMoney+"元，预计获得提成"+moneyOne+"元！";
				
				PreMoney preMoney = getPreMoney( invitingUser.getId(),orderNum,orderTotalMoney,moneyOne,note,orderDate);
				preMoneys.add(preMoney);
				//添加云店用户
			    //marketUsers.add(resetMarketUserPreMoney(invitingUser,moneyOne));
			    
			    sendMsgToUserOnly(invitingUser, note);
			}
		    
		    //查找商家的上上级信息
			MarketUser topInvitingUser = marketUserDao.selectByPrimaryKey(invitingUser.getInvitingId());
			if( null != topInvitingUser ){
				String successPeopleTwo = "0";
				if( StringHelper.isNotBlank(topInvitingUser.getSuccessPeople()) ){
					successPeopleTwo = topInvitingUser.getSuccessPeople();
				}
				if( NumberStringHelper.isGreater(successPeopleTwo, two ) ){
					String moneyTwo = getPercentMoney(money, twoPercent );
					//添加收益记录
					//String note = "VIP用户***成功付款,预计赚取下下级店主“"+user.getUserNickName()+"”的佣金提成"+moneyTwo+"元!";
					String note = "您的二级云店主【"+tgwName+"】分享了京东商品《"+productName+"》已有人购买生成订单"+orderTotalMoney+"元，预计获得提成"+moneyTwo+"元！";
					PreMoney preMoney = getPreMoney( topInvitingUser.getId(),orderNum,orderTotalMoney,moneyTwo,note,orderDate);
					preMoneys.add(preMoney);
					//添加云店用户
    			    //marketUsers.add(resetMarketUserPreMoney(topInvitingUser,moneyTwo));
    			    sendMsgToUserOnly(topInvitingUser, note);
				}
			}
			
		}
		
		//更新数据
		/*if( marketUsers.size() > 0 ){
  			for( MarketUser temp : marketUsers ){
  				marketUserDao.updateByPrimaryKeySelective(temp);
  			}
  		}*/
		if( preMoneys.size() > 0 ){
  			for( PreMoney temp : preMoneys ){
  				preMoneyDao.insert(temp);
  			}
  		}
  	}
  	
  	/**
 	  * 添加上级和上上级的预计收益
 	  * @param user
 	  * @param money
 	  */
 	public void addTopJdPreMoneyOne( MarketUser user, String money, String orderNum,String orderTotalMoney,String productName,String tgwName,Date orderDate){
 		
 		List<MarketUser> marketUsers = new ArrayList<MarketUser>();//可为null
		//List<MarketProfit> marketProfits = new ArrayList<MarketProfit>();
		List<PreMoney> preMoneys = new ArrayList<PreMoney>();
		
		//给店主的佣金
		//String noteUser = "VIP用户***在京东购买了您分享的商品,预计获得佣金"+money+"元！";
		//String noteUser = "您分享的京东商品【"+productName+"】已有人购买生成订单"+orderTotalMoney+"元，预计将获得佣金"+money+"元！";
		
		//PreMoney preMoneyUser = getPreMoney( user.getId(),orderNum,orderTotalMoney,money,noteUser,orderDate);
		//preMoneys.add(preMoneyUser);
		//添加云店用户
	    //marketUsers.add(resetMarketUserPreMoney(user,money));
	    
		//添加云店用户
	    //sendMsgToUserOnly(user, noteUser);
 	    //添加三级分销的功能提成
		String one = sysSettingDao.getByKey("MARKET_SET_ONE_PEOPLE");
		String two = sysSettingDao.getByKey("MARKET_SET_TWO_PEOPLE");
		String onePercent = sysSettingDao.getByKey("MARKET_SET_ONE_PERCENT");
		String twoPercent = sysSettingDao.getByKey("MARKET_SET_TWO_PERCENT");
		//查找商家的上级信息，是否满足一级条件，如果满足则添加相应的金额 
		MarketUser invitingUser = marketUserDao.selectByPrimaryKey(user.getInvitingId());
		String successPeople = "0";
		if( null != invitingUser && StringHelper.isNotBlank(invitingUser.getSuccessPeople()) ){
			successPeople = invitingUser.getSuccessPeople();
		}
		//添加上级的预计收益信息
		if( null != invitingUser ){
			
			if( NumberStringHelper.isGreater(successPeople, one ) ){
				String moneyOne = getPercentMoney(money, onePercent );
				//添加预计收益记录
				//String note = "VIP用户***成功付款,预计赚取下级店主“"+user.getUserNickName()+"”的佣金提成"+moneyOne+"元!";
				String note = "您的一级云店主【"+tgwName+"】分享了京东商品《"+productName+"》已有人购买生成订单"+orderTotalMoney+"元，预计获得提成"+moneyOne+"元！";
				
				PreMoney preMoney = getPreMoney( invitingUser.getId(),orderNum,orderTotalMoney,moneyOne,note,orderDate);
				preMoneys.add(preMoney);
				//添加云店用户
			    marketUsers.add(resetMarketUserPreMoney(invitingUser,moneyOne));
			    
			    sendMsgToUserOnly(invitingUser, note);
			}
		    
		    //查找商家的上上级信息
			MarketUser topInvitingUser = marketUserDao.selectByPrimaryKey(invitingUser.getInvitingId());
			if( null != topInvitingUser ){
				String successPeopleTwo = "0";
				if( StringHelper.isNotBlank(topInvitingUser.getSuccessPeople()) ){
					successPeopleTwo = topInvitingUser.getSuccessPeople();
				}
				if( NumberStringHelper.isGreater(successPeopleTwo, two ) ){
					String moneyTwo = getPercentMoney(money, twoPercent );
					//添加收益记录
					//String note = "VIP用户***成功付款,预计赚取下下级店主“"+user.getUserNickName()+"”的佣金提成"+moneyTwo+"元!";
					String note = "您的二级云店主【"+tgwName+"】分享了京东商品《"+productName+"》已有人购买生成订单"+orderTotalMoney+"元，预计获得提成"+moneyTwo+"元！";
					PreMoney preMoney = getPreMoney( topInvitingUser.getId(),orderNum,orderTotalMoney,moneyTwo,note,orderDate);
					preMoneys.add(preMoney);
					//添加云店用户
   			    marketUsers.add(resetMarketUserPreMoney(topInvitingUser,moneyTwo));
   			    
   			    sendMsgToUserOnly(topInvitingUser, note);
				}
			}
			
		}
		
		//更新数据
		if( marketUsers.size() > 0 ){
 			for( MarketUser temp : marketUsers ){
 				marketUserDao.updateByPrimaryKeySelective(temp);
 			}
 		}
		if( preMoneys.size() > 0 ){
 			for( PreMoney temp : preMoneys ){
 				preMoneyDao.insert(temp);
 			}
 		}
 	}
  	
 	/**
	  * 添加上级和上上级的预计收益
	  * @param user
	  * @param money
	  */
	public void addTopJdPreMoneyOverOne( MarketUser user, OrderJd orderJd,String productName ){
		
		List<MarketUser> marketUsers = new ArrayList<MarketUser>();//可为null
		List<ProfitMoney> profitMarkets = new ArrayList<ProfitMoney>();
		List<PreMoney> preMoneys = new ArrayList<PreMoney>();
		
		//给店主的佣金
		//String noteUser = "VIP用户***在京东购买了您分享的商品,预计获得佣金"+orderJd.getMarketProfit()+"元！";
		//String noteUser = "您分享的京东商品【"+productName+"】已有人购买生成订单"+orderJd.getOrderTotalMoney()+"元，预计将获得佣金"+orderJd.getMarketProfit()+"元！";
		//PreMoney preMoneyUser = getPreMoney( user.getId(),orderJd.getOrderNum(),orderJd.getOrderTotalMoney(),orderJd.getMarketProfit(),noteUser,orderJd.getOrderDate());
		//preMoneyUser.setIsGive(DBConst.TRUE);
		//preMoneys.add(preMoneyUser);
		//ProfitMoney profit = getProfitMoney( user,orderJd,preMoneyUser,productName);
		//profitMarkets.add(profit);
		//添加云店用户的收益，但不减掉用户的预计收益
	    //marketUsers.add(resetMarketUserProfitMoneyOnly(user,orderJd.getMarketProfit()));
	    String sendmsg="订单"+orderJd.getOrderNum()+"已结算了，快快登录APP内『收入明细』查看您的收益吧！";
	    //sendMsgToUser(user,sendmsg);
	    
	    //添加三级分销的功能提成
		String one = sysSettingDao.getByKey("MARKET_SET_ONE_PEOPLE");
		String two = sysSettingDao.getByKey("MARKET_SET_TWO_PEOPLE");
		String onePercent = sysSettingDao.getByKey("MARKET_SET_ONE_PERCENT");
		String twoPercent = sysSettingDao.getByKey("MARKET_SET_TWO_PERCENT");
		//查找商家的上级信息，是否满足一级条件，如果满足则添加相应的金额 
		MarketUser invitingUser = marketUserDao.selectByPrimaryKey(user.getInvitingId());
		String successPeople = "0";
		if( null != invitingUser && StringHelper.isNotBlank(invitingUser.getSuccessPeople()) ){
			successPeople = invitingUser.getSuccessPeople();
			
			if( NumberStringHelper.isGreater(successPeople, one ) ){
				String moneyOne = getPercentMoney(orderJd.getMarketProfit(), onePercent );
				//添加预计收益记录
				//String note = "VIP用户***成功付款,预计赚取下级店主“"+user.getUserNickName()+"”的佣金提成"+moneyOne+"元!";
				String note = "您的一级云店主【"+user.getUserNickName()+"】分享了京东商品《"+productName+"》已有人购买生成订单"+orderJd.getOrderTotalMoney()+"元，预计获得提成"+moneyOne+"元！";
				PreMoney preMoney = getPreMoney( invitingUser.getId(),orderJd.getOrderNum(),orderJd.getOrderTotalMoney(),moneyOne,note,orderJd.getOrderDate());
				preMoney.setIsGive(DBConst.TRUE);
				preMoneys.add(preMoney);
				ProfitMoney profitOne = getProfitMoney( invitingUser,orderJd,preMoney,productName);
				profitMarkets.add(profitOne);
				//添加云店用户
			    marketUsers.add(resetMarketUserProfitMoneyOnly(invitingUser,moneyOne));
			   // String sendmsg="订单"+orderJd.getOrderNum()+"已结算了，快快登录APP内『收入明细』查看您的收益吧！";
			    sendMsgToUser(invitingUser,sendmsg);
			}
		    
		    //查找商家的上上级信息
			MarketUser topInvitingUser = marketUserDao.selectByPrimaryKey(invitingUser.getInvitingId());
			if( null != topInvitingUser ){
				String successPeopleTwo = "0";
				if( StringHelper.isNotBlank(topInvitingUser.getSuccessPeople()) ){
					successPeopleTwo = topInvitingUser.getSuccessPeople();
				}
				if( NumberStringHelper.isGreater(successPeopleTwo, two ) ){
					String moneyTwo = getPercentMoney(orderJd.getMarketProfit(), twoPercent );
					//添加收益记录
					//String note = "VIP用户***成功付款,预计赚取下下级店主“"+user.getUserNickName()+"”的佣金提成"+moneyTwo+"元!";
					String note = "您的二级云店主【"+user.getUserNickName()+"】分享了京东商品《"+productName+"》已有人购买生成订单"+orderJd.getOrderTotalMoney()+"元，预计获得提成"+moneyTwo+"元！";
					PreMoney preMoney = getPreMoney( topInvitingUser.getId(),orderJd.getOrderNum(),orderJd.getOrderTotalMoney(),moneyTwo,note,orderJd.getOrderDate());
					preMoney.setIsGive(DBConst.TRUE);
					preMoneys.add(preMoney);
					ProfitMoney profitMoney = getProfitMoney( topInvitingUser,orderJd,preMoney,productName );
					profitMarkets.add(profitMoney);
					//添加云店用户
  			        marketUsers.add(resetMarketUserProfitMoneyOnly(topInvitingUser,moneyTwo));
  			    
  			        sendMsgToUser(topInvitingUser,sendmsg);
				}
			}
		}
		
		//更新数据
		if( marketUsers.size() > 0 ){
			for( MarketUser temp : marketUsers ){
				marketUserDao.updateByPrimaryKeySelective(temp);
			}
		}
		if( preMoneys.size() > 0 ){
			for( PreMoney temp : preMoneys ){
				preMoneyDao.insert(temp);
			}
		}
		if( profitMarkets.size()>0 ){
			for( ProfitMoney temp: profitMarkets ){
				profitMoneyDao.insert(temp);
			}
		}
	}
 	
  	/**
 	  * 添加上级和上上级的预计收益
 	  * @param user
 	  * @param money
 	  */
 	public void addTopJdPreMoneyOver( MarketUser user, OrderJd orderJd,String productName ){
 		
 		String orderNum = orderJd.getOrderNum();
 		if( orderNum.equals("72194287951") ){
 			System.out.println("aaa");
 		}
 		
 		List<MarketUser> marketUsers = new ArrayList<MarketUser>();//可为null
		List<ProfitMoney> profitMarkets = new ArrayList<ProfitMoney>();
		List<PreMoney> preMoneys = new ArrayList<PreMoney>();
		
		//给店主的佣金
		//String noteUser = "VIP用户***在京东购买了您分享的商品,预计获得佣金"+orderJd.getMarketProfit()+"元！";
		String noteUser = "您分享的京东商品【"+productName+"】已有人购买生成订单"+orderJd.getOrderTotalMoney()+"元，预计将获得佣金"+orderJd.getMarketProfit()+"元！";
		PreMoney preMoneyUser = getPreMoney( user.getId(),orderJd.getOrderNum(),orderJd.getOrderTotalMoney(),orderJd.getMarketProfit(),noteUser,orderJd.getOrderDate());
		preMoneyUser.setIsGive(DBConst.TRUE);
		preMoneys.add(preMoneyUser);
		ProfitMoney profit = getProfitMoney( user,orderJd,preMoneyUser,productName);
		profitMarkets.add(profit);
		//添加云店用户的收益，但不减掉用户的预计收益
	    marketUsers.add(resetMarketUserProfitMoneyOnly(user,orderJd.getMarketProfit()));
	    String sendmsg="订单"+orderJd.getOrderNum()+"已结算了，快快登录APP内『收入明细』查看您的收益吧！";
	    sendMsgToUser(user,sendmsg);
	    
 	    //添加三级分销的功能提成
		String one = sysSettingDao.getByKey("MARKET_SET_ONE_PEOPLE");
		String two = sysSettingDao.getByKey("MARKET_SET_TWO_PEOPLE");
		String onePercent = sysSettingDao.getByKey("MARKET_SET_ONE_PERCENT");
		String twoPercent = sysSettingDao.getByKey("MARKET_SET_TWO_PERCENT");
		//查找商家的上级信息，是否满足一级条件，如果满足则添加相应的金额 
		MarketUser invitingUser = marketUserDao.selectByPrimaryKey(user.getInvitingId());
		String successPeople = "0";
		if( null != invitingUser && StringHelper.isNotBlank(invitingUser.getSuccessPeople()) ){
			successPeople = invitingUser.getSuccessPeople();
			
			if( NumberStringHelper.isGreater(successPeople, one ) ){
				String moneyOne = getPercentMoney(orderJd.getMarketProfit(), onePercent );
				//添加预计收益记录
				//String note = "VIP用户***成功付款,预计赚取下级店主“"+user.getUserNickName()+"”的佣金提成"+moneyOne+"元!";
				String note = "您的一级云店主【"+user.getUserNickName()+"】分享了京东商品《"+productName+"》已有人购买生成订单"+orderJd.getOrderTotalMoney()+"元，预计获得提成"+moneyOne+"元！";
				PreMoney preMoney = getPreMoney( invitingUser.getId(),orderJd.getOrderNum(),orderJd.getOrderTotalMoney(),moneyOne,note,orderJd.getOrderDate());
				preMoney.setIsGive(DBConst.TRUE);
				preMoneys.add(preMoney);
				ProfitMoney profitOne = getProfitMoney( invitingUser,orderJd,preMoney,productName);
				profitMarkets.add(profitOne);
				//添加云店用户
			    marketUsers.add(resetMarketUserProfitMoneyOnly(invitingUser,moneyOne));
			   // String sendmsg="订单"+orderJd.getOrderNum()+"已结算了，快快登录APP内『收入明细』查看您的收益吧！";
			    sendMsgToUser(invitingUser,sendmsg);
			}
		    
		    //查找商家的上上级信息
			MarketUser topInvitingUser = marketUserDao.selectByPrimaryKey(invitingUser.getInvitingId());
			if( null != topInvitingUser ){
				String successPeopleTwo = "0";
				if( StringHelper.isNotBlank(topInvitingUser.getSuccessPeople()) ){
					successPeopleTwo = topInvitingUser.getSuccessPeople();
				}
				if( NumberStringHelper.isGreater(successPeopleTwo, two ) ){
					String moneyTwo = getPercentMoney(orderJd.getMarketProfit(), twoPercent );
					//添加收益记录
					//String note = "VIP用户***成功付款,预计赚取下下级店主“"+user.getUserNickName()+"”的佣金提成"+moneyTwo+"元!";
					String note = "您的二级云店主【"+user.getUserNickName()+"】分享了京东商品《"+productName+"》已有人购买生成订单"+orderJd.getOrderTotalMoney()+"元，预计获得提成"+moneyTwo+"元！";
					PreMoney preMoney = getPreMoney( topInvitingUser.getId(),orderJd.getOrderNum(),orderJd.getOrderTotalMoney(),moneyTwo,note,orderJd.getOrderDate());
					preMoney.setIsGive(DBConst.TRUE);
					preMoneys.add(preMoney);
					ProfitMoney profitMoney = getProfitMoney( topInvitingUser,orderJd,preMoney,productName );
					profitMarkets.add(profitMoney);
					//添加云店用户
   			        marketUsers.add(resetMarketUserProfitMoneyOnly(topInvitingUser,moneyTwo));
   			    
   			        sendMsgToUser(topInvitingUser,sendmsg);
				}
			}
		}
		
		//更新数据
		if( marketUsers.size() > 0 ){
 			for( MarketUser temp : marketUsers ){
 				marketUserDao.updateByPrimaryKeySelective(temp);
 			}
 		}
		if( preMoneys.size() > 0 ){
 			for( PreMoney temp : preMoneys ){
 				preMoneyDao.insert(temp);
 			}
 		}
		if( profitMarkets.size()>0 ){
			for( ProfitMoney temp: profitMarkets ){
				profitMoneyDao.insert(temp);
			}
		}
 	}
 	
 	

 	private void sendMsgToUserOnly( MarketUser user,String msg ){
 		String byKey = sysSettingDao.getByKey("IS_MSG_TEST");//是否测试信息
 		if( "0".equals(byKey) ){
 		    pushMsg(user.getId(), msg);
 		}else{
 			pushMsg("beaae7e827074ba796de2c6e88bffb73",msg);
 		}
 	}
 	
 	private void sendMsgToUser( MarketUser user,String msg ){
 		String byKey = sysSettingDao.getByKey("IS_MSG_TEST");//是否测试信息
 		if( "0".equals(byKey) ){
 			//消息推送+短信提醒
 		    if( StringHelper.isNotBlank(user.getUserPhone()) ){
 		    	sendMassage(user.getUserPhone(),msg);
 		    }
 		    pushMsg(user.getId(), msg);
 		}else{
 			//消息推送+短信提醒
 		    if( StringHelper.isNotBlank(user.getUserPhone()) ){
 		    	sendMassage("18401762162",msg);
 		    }
 			pushMsg("beaae7e827074ba796de2c6e88bffb73",msg);
 		}
 	}
 	

 	/**
 	 * 添加用户的总收益，但是不减掉用户的预计收益
 	 */
  	private MarketUser resetMarketUserProfitMoneyOnly(MarketUser invitingUser, String moneyOne) {
  		//添加收益
  		String userMoney = "0";
  		if( StringHelper.isNotBlank(invitingUser.getMoney()) ){
  			userMoney = invitingUser.getMoney();
  		}
  		userMoney = NumberStringHelper.addString(userMoney, moneyOne);
  		invitingUser.setMoney(userMoney);
  		
  		//添加总收益
  		String totalMoney = "0";
  		if( StringHelper.isNotBlank(invitingUser.getTotalProfit()) ){
  			totalMoney = invitingUser.getTotalProfit();
  		}
  		totalMoney = NumberStringHelper.addString(totalMoney, moneyOne);
  		invitingUser.setTotalProfit(totalMoney);
  		//添加产品总数
		String totalProduct = "0";
		if( StringHelper.isNotBlank(invitingUser.getTotalProduct()) ){
			totalProduct = invitingUser.getTotalProduct();
		}
		totalProduct = NumberStringHelper.addString(totalProduct,"1");
		invitingUser.setTotalProduct(totalProduct);
  		return invitingUser;
	}

	/**
  	 * 添加店主用户的预计收益 
  	 */
  	public MarketUser resetMarketUserPreMoney( MarketUser user,String preMoney ){
  		String userPreMoney = "0";
  		if( StringHelper.isNotBlank(user.getPreProfit()) ){
  			userPreMoney = user.getPreProfit();
  		}
  		userPreMoney = NumberStringHelper.addString(userPreMoney, preMoney);
  		user.setPreProfit(userPreMoney);
  		return user;
  	}
  	
  	/**
     * 
     * @param order 订单
     * @param user VIP购买用户
     * @param money 云店用户
     * @param note 备注信息
     * @param type 类型
     * @return
     */
    public PreMoney getPreMoney( String userId, String orderNum, String totalMoney, String money, String note,Date orderDate ){
    	PreMoney preMoney = new PreMoney();
		this.initDefalutFields(preMoney);
		preMoney.setNote(note);
		preMoney.setMarketUserId(userId);
		//业务字段
		preMoney.setPreMoney(money);
		preMoney.setIsGive(DBConst.FALSE);
		preMoney.setIsCancel(DBConst.FALSE);
		preMoney.setOrderId(IdGen.uuid());
		preMoney.setOrderNum(orderNum);
		preMoney.setOrderTotalMoney(totalMoney);
		preMoney.setOrderDate(orderDate);
    	return preMoney;
    }
  	
  	 /**
     * 返回一个百分比的金额
     * @param money
     * @param percent
     * @return
     */
    public String getPercentMoney( String money, String percent ){
    	String replace = percent.replace("%", "");
    	String mulString = NumberStringHelper.mulString(money, replace);
    	String divString = NumberStringHelper.divString(mulString, "100", 2);
    	return divString;
    }
  	
  	/**
  	 * 添加预计收益
  	 * 
  	 */
	public void addJdPreMoney( MarketUser user, List<PreMoney> preMoneys ){
  			
  		marketUserDao.updateByPrimaryKey(user);
  		
  		if( preMoneys.size() > 0 ){
  			for( PreMoney temp : preMoneys ){
  				preMoneyDao.insert(temp);
  			}
  		}
  		
  	}
  	 
  	 public String getOrderjdId( String ordernum ){
  		 String orderId = "";
  		 OrderJdExample example = new OrderJdExample();
  		 example.setOrderByClause("CREATE_TIME DESC");
  		 com.itic.mall.system.orderjd.persistence.model.OrderJdExample.Criteria criteria = example.createCriteria();
  		 criteria.andIsEffectiveEqualTo(DBConst.TRUE);
  		 criteria.andOrderNumEqualTo(ordernum);
  		 List<OrderJd> list = orderJdDao.selectByExample(example);
  		 if( list.size()>0 ){
  			orderId = list.get(0).getId();
  		 }
  		 
  		 if( list.size()>1 ){
 			 OrderJd orderJd = list.get(1);
 			 orderJdDao.deleteByPrimaryKey(orderJd.getId());
 			 
 		 }
  		 return orderId;
      } 

  	 
  	 private String getOrderJdProductsIdBySkuIdAndOrderId(String skuId, String id) {
  		 String result = "";
  		 OrderJdProductsExample example = new OrderJdProductsExample();
  		 example.setOrderByClause("CREATE_TIME DESC");
  		 com.itic.mall.system.orderjdproducts.persistence.model.OrderJdProductsExample.Criteria criteria = example.createCriteria();
  		 criteria.andIsEffectiveEqualTo(DBConst.TRUE);
  		 criteria.andSkuIdEqualTo(skuId);
  		 criteria.andOrderIdEqualTo(id);
  		 
  		 List<OrderJdProducts> list = orderJdProductsDao.selectByExample(example);
  		 if( list.size()>0 ){
  			 result = list.get(0).getId();
  		 }
  		 if( list.size()>1 ){
  			 OrderJdProducts orderJdProducts = list.get(1);
  			 orderJdProductsDao.deleteByPrimaryKey(orderJdProducts.getId());
  		 }
		 return result;
	}

    

    
    /**
     * 京东已结算的订单
     * @param string
     */
	public void subSyncJdOrderOver(String daytime) {
		    try {
			    //以当前时间来算吧，每小时同步一次订单数据 一天同步24次，
		    	String SERVER_URL = MallJdConfig.getUrl();//搜索有效商品信息
				String accessToken = sysSettingDao.getByKey("JD_ACCESS_TOKEN");//京东TOKEN
		    	String appKey = MallJdConfig.getKey();
		    	String appSecret = MallJdConfig.getSecret();
		    	long unionId = MallJdConfig.getUnionId();
		    	
		    	JdClient client = new DefaultJdClient(SERVER_URL,accessToken,appKey,appSecret); 
				UnionServiceQueryCommissionOrdersRequest request=new UnionServiceQueryCommissionOrdersRequest();
	
				request.setUnionId( unionId );
				request.setTime( daytime );
				request.setPageIndex( 0 );
				request.setPageSize( 1000 );

			
				UnionServiceQueryCommissionOrdersResponse response=client.execute(request);
				if( "0".equals(response.getCode()) ){
					String ordersResult = response.getQueryCommissionOrdersResult();
					if(ordersResult.contains("data")){
						net.sf.json.JSONObject object = new net.sf.json.JSONObject();
						@SuppressWarnings("static-access")
						net.sf.json.JSONObject fromObject = object.fromObject(ordersResult);
						syncDataOver(fromObject);
					}
				}
				
			} catch (JdException e) {
				e.printStackTrace();
			}
	}

	/**
	 * @param orderJd //京东订单信息
	 * @param jiesuanTime //京东的结算时间
	 * @param commission //京东返回的总佣金金额
	 */
	public void jiesuan( List<PreMoney> listP, OrderJd orderJd, Date jiesuanTime, String commission,String productName ){
		
		String orderNum = orderJd.getOrderNum();
		if( orderNum.equals("72194287951")){
			System.out.println("");
		}
		
		//将京东订单变成已结算
		orderJd.setIsJiesuan("已结算");
		orderJd.setJiesuanTime(jiesuanTime);
		orderJd.setOverCommisions(commission);
		//与店主对半平分
		String overMarketProfit = NumberStringHelper.divString(commission,"2",2);
		orderJd.setOverMarketProfit(overMarketProfit);
		
		//更新订单状态
		orderJdDao.updateByPrimaryKeySelective(orderJd);
		
		if( listP.size()>0 ){
			for( PreMoney temp : listP ){
				if( "0".equals(temp.getIsGive()) ){
					String userId = temp.getMarketUserId();
					String preMoney = temp.getPreMoney();
					temp.setIsGive("1");
					preMoneyDao.updateByPrimaryKeySelective(temp);
					
					MarketUser marketUser = marketUserDao.selectByPrimaryKey(userId);
					if( null != marketUser ){
						//减少预计收益
						//String preProfit = "0";
						//if( StringHelper.isNotBlank(marketUser.getPreProfit())){
							//preProfit = marketUser.getPreProfit();
						//}
						
						//preProfit = NumberStringHelper.subtractString(preProfit, preMoney);
						//marketUser.setPreProfit(preProfit);
						//添加实际收益
						String money = "0";
						if( StringHelper.isNotBlank(marketUser.getMoney()) ){
							money = marketUser.getMoney();
						}
						money = NumberStringHelper.addString(money, preMoney);
						marketUser.setMoney(money);
						//添加用户的总收益
						String totalMoney = "0";
						if( StringHelper.isNotBlank(marketUser.getTotalProfit()) ){
							totalMoney = marketUser.getTotalProfit();
						}
						totalMoney = NumberStringHelper.addString(totalMoney, preMoney);
						marketUser.setTotalProfit(totalMoney);
						//添加产品总数
						String totalProduct = "0";
						if( StringHelper.isNotBlank(marketUser.getTotalProduct()) ){
							totalProduct = marketUser.getTotalProduct();
						}
						totalProduct = NumberStringHelper.addString(totalProduct,"1");
						marketUser.setTotalProduct(totalProduct);
						
						marketUserDao.updateByPrimaryKeySelective(marketUser);
						//添加收益明细
						ProfitMoney profitMoney = getProfitMoney(marketUser,orderJd,temp,productName);
						
						profitMoneyDao.insert(profitMoney);
						//短信提醒，消息推送
						 //消息推送+短信提醒
						//【友惠家云店】订单70769164332已结算了，快快登录APP内『收入明细』查看您的佣金收益！
						//String sendmsg="订单"+orderJd.getOrderNum()+"已结算了，快快登录APP内『收入明细』查看您的收益吧！";
	    			    //sendMsgToUser(marketUser, sendmsg);
	    			    
					}
					
				}
			}
		}
	}
	
	public ProfitMoney getProfitMoney( MarketUser user,OrderJd orderJd,PreMoney preMoney,String productName ){
		//添加收益记录
		ProfitMoney profitMoney = new ProfitMoney();
		this.initDefalutFields(profitMoney);
		profitMoney.setMarketUserId(user.getId());
		String note = "";
		if(preMoney.getNote().contains("提成")){
			profitMoney.setType("002");
			note = "尊敬的云店主：订单号："+orderJd.getOrderNum()+",商品名称【"+productName+"】,已结算啦！您已获得订单提成"+preMoney.getPreMoney()+"元!";
		}else{
			profitMoney.setType("001");
			note = "尊敬的云店主：订单号："+orderJd.getOrderNum()+",商品名称【"+productName+"】,已结算啦！您已获得订单佣金"+preMoney.getPreMoney()+"元!";
		}
		
		profitMoney.setNote(note);
		profitMoney.setOrderId(orderJd.getId());
		profitMoney.setOrderNum(orderJd.getOrderNum());
		profitMoney.setMoney(preMoney.getPreMoney());
		if( StringHelper.isNotBlank(orderJd.getUserId()) ){
			profitMoney.setUserId(orderJd.getUserId());
		}else{
			profitMoney.setUserId("unknown");
		}
		profitMoney.setOrderPayTime(new Date());
		profitMoney.setOrderTotalMoney(orderJd.getOrderTotalMoney());
		profitMoney.setPreMoneyId(preMoney.getId());
		
		profitMoney.setUserNickName(EmojiHelper.filterEmoji(user.getUserNickName()));//店主名称
		return profitMoney;
	}
	

	public void syncJdOrderOneDayOver(String dateStringByDate) {
		int hour=24;
  		for( int i=hour;i>=0;i-- ){
  			subSyncJdOrderOver(dateStringByDate+i+"");
  		}
	}
	
	
    	
	public ProductJd getBySku( String sku ){
		ProductJd result = null;
		ProductJdExample example = new ProductJdExample();
		example.setOrderByClause("CREATE_TIME DESC");
		com.itic.mall.system.productjd.persistence.model.ProductJdExample.Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andSkuEqualTo(sku);
		List<ProductJd> list = productJdDao.selectByExample(example);
		if( list.size()>0 ){
			result = list.get(0);
		}
		if( list.size()>1 ){
			productJdDao.deleteByPrimaryKey(list.get(1).getId());
		}
		return result;
	}
	
    
    /**
     * 发送验证码通用方法（注册与修改密码需要用到）
     * @param telphone  手机号码
     * @return
     */
    public String sendMassage(String telphone,String text){
	
    	String result = FAILED;
    	
    	HttpClient client = new HttpClient(); 
		PostMethod method = new PostMethod(Url); 
			
		//client.getParams().setContentCharset("GBK");		
		client.getParams().setContentCharset("UTF-8");
		method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

		//String content = new String("您的验证码是："+codeCont+"。请不要把验证码泄露给其他人。"); 
	    String content = new String(text);
		// 您的验证码是：【变量】，3分钟有效时间，请不要把验证码泄露给其他人。
	    NameValuePair[] data = {//提交短信
			    //new NameValuePair("account", "cf_jdhj"), 
			    //new NameValuePair("password", "a123456"), //密码可以使用明文密码或使用32位MD5加密
			    new NameValuePair("account", "C11714710"), 
			    new NameValuePair("password", "85202a35086eb358e717dbf9ebc6e9bc"), //密码可以使用明文密码或使用32位MD5加密
			    //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
			    new NameValuePair("mobile", telphone), 
			    new NameValuePair("content", content),
		};
		
		method.setRequestBody(data);		
		
		
		try {
			client.executeMethod(method);	
			 
			String SubmitResult =method.getResponseBodyAsString();
					
			//System.out.println(SubmitResult);

			Document doc = DocumentHelper.parseText(SubmitResult); 
			Element root = doc.getRootElement();


			String code = root.elementText("code");	
			//String msg = root.elementText("msg");	
			//String smsid = root.elementText("smsid");	
			
			
			//System.out.println(code);
			//System.out.println(msg);
			//System.out.println(smsid);
						
			if("2".equals(code)){
				result = SUCCESS;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}	
	    
		return result;
    }
    
    private String getMarketProfit(String commission) {
  		String marketProfit = NumberStringHelper.divString(commission, "1.8", 2);
		return marketProfit;
	}
  	 
  	
  	public void cancelPreMoney( String orderId ){
  		PreMoneyExample exampleP = new PreMoneyExample();
        exampleP.createCriteria().andOrderNumEqualTo(orderId);
		List<PreMoney> listP = preMoneyDao.selectByExample(exampleP);
		if( listP.size()>0 ){
			for( PreMoney temp : listP){
				if( DBConst.FALSE.equals(temp.getIsCancel()) ){
					String note = temp.getNote()+"  【用户已取消订单】";
					temp.setNote(note);
					temp.setIsCancel(DBConst.TRUE);
					preMoneyDao.updateByPrimaryKeySelective(temp);
					
					//预计收益减少
					/*String marketUserId = temp.getMarketUserId();
					MarketUser marketUser = marketUserDao.selectByPrimaryKey(marketUserId);
					if( null != marketUser ){
						String preProfit = "0";
						if( StringHelper.isNotBlank(marketUser.getPreProfit()) ){
							preProfit = marketUser.getPreProfit();
						}
						//preProfit = NumberStringHelper.subtractString(preProfit, temp.getPreMoney());
						
						//marketUser.setPreProfit(preProfit);
						//marketUserDao.updateByPrimaryKeySelective(marketUser);
						
					}*/
				}
			}
		}
  	}
  	
  	
  	public void pushMsg( String userId ,String text ){
    	//推送消息到云店主
		 JPushClient jpushClient = new JPushClient(SECREAT, APP_KEY, null, ClientConfig.getInstance());

	    // For push, all you need do is to build PushPayload object.
	    //PushPayload payload = buildPushObject_all_all_alert( text );
	    
		//PushPayload payload = buildPushObject_ios_audienceMore_messageWithExtras( userId,text );
		PushPayload payload = buildPushObject_all_alias_alert(userId,text);
	    try {
	        PushResult tmpres = jpushClient.sendPush(payload);
	       
	        System.out.println(tmpres);
	        //LOG.info("Got result - " + result);

	    } catch (APIConnectionException e) {
	        // Connection error, should retry later
	        //LOG.error("Connection error, should retry later", e);
	    	System.out.println(1);
	    } catch (APIRequestException e) {
	        // Should review the error, and fix the request
	        //LOG.error("Should review the error, and fix the request", e);
	        //LOG.info("HTTP Status: " + e.getStatus());
	       // LOG.info("Error Code: " + e.getErrorCode());
	        //LOG.info("Error Message: " + e.getErrorMessage());
	    	System.out.println(2);
	    }
	    
    }

    public static PushPayload buildPushObject_all_all_alert( String text ) {
        return PushPayload.alertAll(text);
    }
    
    public static PushPayload buildPushObject_all_alias_alert( String userId, String text ) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(userId))
                .setNotification(Notification.alert(text))
                .build();
    }
    
    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras( String userId,String text ) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag(userId))
                        //.addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(text)
                        //.addExtra("from", "JPush")
                        .build())
                .build();
    }
    
    
    public String filterRepeat(){
    	List<String> orderNums = orderJdDao.getRepeatOrderNum();
    	if( orderNums.size()>0 ){
    		for( String temp : orderNums ){
    			PreMoneyExample example = new PreMoneyExample();
    			Criteria criteria = example.createCriteria();
    			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    			criteria.andOrderNumEqualTo(temp);
    			List<PreMoney> list = preMoneyDao.selectByExample(example);
    			
    			List<String> userids = new ArrayList<String>();
    			if( list.size()>3 ){
    				for( PreMoney ttmp : list ){
    					boolean contains = userids.contains(ttmp.getMarketUserId());
    					if(contains){
    						ttmp.setIsEffective(DBConst.FALSE);
    						preMoneyDao.updateByPrimaryKey(ttmp);
    					}else{
    						userids.add(ttmp.getMarketUserId());
    					}
    				}
    			}
    			userids.removeAll(userids);
    		}
    	}
    	return SUCCESS;
    }
}